import { NativeModules } from 'react-native';

interface AudioModuleInterface {
  playAudio(audioData: string): Promise<void>;
  stopAudio(): Promise<void>;
  isPlaying(): Promise<boolean>;
}

const { AudioModule } = NativeModules;

// 简单的内存缓存
const audioCache = new Map<string, { data: string; timestamp: number }>();
const CACHE_DURATION = 10 * 60 * 1000; // 10分钟缓存

class AudioService {
  private module: AudioModuleInterface;
  private isCurrentlyPlaying: boolean = false;

  constructor() {
    this.module = AudioModule;
  }

  // 清理缓存
  private cleanupCache(): void {
    const now = Date.now();
    for (const [key, value] of audioCache.entries()) {
      if (now - value.timestamp > CACHE_DURATION) {
        audioCache.delete(key);
      }
    }
  }

  // 从缓存获取音频
  private getCachedAudio(uri: string): string | null {
    const cached = audioCache.get(uri);
    if (cached && Date.now() - cached.timestamp < CACHE_DURATION) {
      return cached.data;
    }
    return null;
  }

  // 缓存音频数据
  private cacheAudio(uri: string, data: string): void {
    audioCache.set(uri, { data, timestamp: Date.now() });
  }

  // 获取音频数据
  async getAudioData(audioPath: string, serverInfo?: any): Promise<string> {
    console.log('🎵 AudioService 开始获取音频:', audioPath);
    
    // 检查缓存
    const cachedData = this.getCachedAudio(audioPath);
    if (cachedData) {
      console.log('🎵 使用缓存音频数据');
      return cachedData;
    }
    
    // 如果是本地文件路径，直接使用
    if (audioPath.startsWith('audio/') || audioPath.startsWith('file://')) {
      console.log('🎵 使用本地音频文件');
      return audioPath;
    }
    
    // 如果是相对路径，尝试通过 Native Module 获取音频数据
    if (audioPath.startsWith('cards/') || audioPath.includes('audio_')) {
      try {
        console.log('🔄 通过 Native Module 获取音频...');
        
        // 调用 Native Module
        const result = await NativeModules.ApiModule.getAudioData(audioPath, serverInfo);
        console.log('✅ 音频数据获取成功:', result);
        
        if (result && result.data) {
          console.log('🎵 设置音频数据，大小:', result.size);
          // 缓存音频数据
          this.cacheAudio(audioPath, result.data);
          return result.data;
        } else {
          console.warn('⚠️ 音频数据为空');
          throw new Error('音频数据为空');
        }
      } catch (error) {
        console.error('❌ 获取音频数据失败:', error);
        throw error;
      }
    } else {
      // 不是相对路径，直接使用原始路径
      console.log('🎵 使用原始音频路径');
      return audioPath;
    }
  }

  // 播放音频
  async playAudio(audioPath: string, serverInfo?: any): Promise<void> {
    try {
      console.log('🎵 AudioService.playAudio 开始:', {
        audioPath,
        serverInfo,
        isCurrentlyPlaying: this.isCurrentlyPlaying
      });
      
      if (this.isCurrentlyPlaying) {
        console.log('🛑 停止当前播放');
        await this.stopAudio();
      }

      console.log('🎵 获取音频数据...');
      const audioData = await this.getAudioData(audioPath, serverInfo);
      console.log('🎵 获取到的音频数据:', {
        audioData: audioData.substring(0, 100) + '...',
        dataType: typeof audioData,
        isBase64: audioData.startsWith('data:audio/mpeg;base64,') || audioData.startsWith('audio/')
      });
      
      console.log('🎵 调用原生模块播放音频...');
      await this.module.playAudio(audioData);
      this.isCurrentlyPlaying = true;
      console.log('✅ 音频播放开始');
    } catch (error) {
      console.error('❌ 音频播放失败:', error);
      this.isCurrentlyPlaying = false;
      throw error;
    }
  }

  // 停止音频
  async stopAudio(): Promise<void> {
    try {
      console.log('🛑 停止音频播放');
      await this.module.stopAudio();
      this.isCurrentlyPlaying = false;
      console.log('✅ 音频播放已停止');
    } catch (error) {
      console.error('❌ 停止音频失败:', error);
      throw error;
    }
  }

  // 检查是否正在播放
  async isPlaying(): Promise<boolean> {
    try {
      const playing = await this.module.isPlaying();
      this.isCurrentlyPlaying = playing;
      return playing;
    } catch (error) {
      console.error('❌ 检查播放状态失败:', error);
      return false;
    }
  }

  // 定期清理缓存
  startCacheCleanup(): void {
    setInterval(() => {
      this.cleanupCache();
    }, CACHE_DURATION);
  }

  // 清理资源
  cleanup(): void {
    // 清理缓存
    this.cleanupCache();
  }
}

export default new AudioService(); 